<?php

namespace App\Http\Controllers;

use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Requests\SendMessageRequest;
use App\Models\VerifyCode;
use App\Service\SendSms;
use Illuminate\Support\Facades\Log;


class SendMessageController extends Controller
{
    protected $sendSms;
    public function __construct(SendSms $sendSms)
    {
        $this->sendSms=$sendSms;
    }

    public function send(SendMessageRequest $request)
    {
        $mobile = $request->input('mobile');
        $sms = app('sms');
        $code = rand(1000, 9999);
        $verifyCode = VerifyCode::where('account', $mobile)->first();
        if ($verifyCode) {
            $time = $verifyCode->updated_at ?? $verifyCode->created_at;
            if (strtotime(now()) - strtotime($time) < 60) {
                throw new ApiException('短信发送太频繁');
            }
        } else {
            $verifyCode = new VerifyCode();
            $verifyCode->account = $mobile;
        }
        try {
          $this->sendSms->sendSms($mobile,$code);
        } catch (\Exception $exception) {
            Log::error($exception->getMessage());
            throw  new ApiException('短信发送失败');
        }
        $verifyCode->verify_code_num = $code;
        $verifyCode->save();
        return response()->json([
            'code' => 200,
            'message'=>'短信发送成功',
            'data' => [],
        ]);
    }
}
